<?php

/**
 * randomStr generates a random string as password
 *
 * @param integer $car number of caracters of the result string
 * @return string
 * @author Romain Venturi 
 */
function randomStr($car)
	{ 
		$string = ""; 
		$chaine = "abcdefghijklmnpqrstuvwxy"; 
		srand((double)microtime()*1000000); 
		for($i=0; $i<$car; $i++) { 
			$string .= $chaine[rand()%strlen($chaine)]; 
		} 
		return $string; 
	}

/**
* Controller des Intervenants
*/

class UsersController extends AppController
{
	var $name = "Users";
	var $helpers = array('Html', 'Form', 'Format');
	var $components = array('UserAuth', 'ContentRight', 'Cookie');
	var $uses = array('User','Company','Project','Status');
//	var $scaffold;
	
	public function beforeFilter()
	{
		$this->set('project_id', 0);
		$this->set('project_name', "");
	}

	public function index()
	{
		$user = $this->Session->read('User');
		if ($user) {
			$this->set('user', $user['User']);
			$this->set('roles', $user['Role']);
			// pr ($this->Cookie->read('User'));
			$this->log("Look like ".$user['User']['login']." just logged in.", LOG_DEBUG);
		} else {
			$this->redirect('login');
		}
	}

	public function select()
	{
		$project_id = $this->params['form']['project_id'];
		if (empty($project_id) == false) {
			$project = $this->Project->findById($project_id);
			$this->UserAuth->checkPermission($project_id);
			$this->redirect('/' . $project['Project']['rewrite_name'] . '/'. $project_id . '/projects');
		} else
			$this->redirect('/');
	}

	/**
	 * Return the list of all users
	 *
	 * @author Kévin Labesse
	 **/
	public function liste()
	{
		if ($this->UserAuth->isAdmin() == false && $this->UserAuth->isDP() == false && $this->UserAuth->isTL() == false) {
			$this->Session->setFlash('Failure, you don\'t have the right to access this area.');
			$this->redirect ('/');
		}
		$this->User->unbindModel(array('hasMany' => array('Role')));		
		$this->set('users', $this->User->findAll(null, null, array('User.lastname')));	
	}

	/**
	 * index is the main function which displays stakeholders page and the add form.
	 *
	 * @return void
	 * @author Romain Venturi 
	 */
	public function lists()
	{
		if (empty($this->data)) {
			$project_id = $this->params['projectId'];
			$this->set('project_id', $project_id);
			$this->set('project_name', $this->params['projectName']);
			if ($project_id != null) {
				$this->UserAuth->checkPermission($project_id);
				$this->Company->unbindModel(array('hasMany' => array('Project')));
				$clientList = $this->Company->findAll();
				$this->User->unbindModel(array('belongsTo' => array('Company'), 'hasMany' => array('Role')));
				$userList = $this->User->findAll();
				$this->set('clientList', $clientList);
				$this->set('userList', $userList);
				$statusList = $this->Status->findAll();
				$this->set('statusList', $statusList);
				$this->Project->Company->unbindModel(array('hasMany' => array('Project')));
				$this->Project->Role->unbindModel(array('belongsTo' => array('Project')));
				$this->Project->unbindModel(array('hasMany'=> array('Document', 'Batch')));
				$object = $this->Project->findAllById($project_id, null, null, null, 1, 3);
				$this->set('object', $object);
				if ($this->UserAuth->checkAcces($project_id, 'project_user_add'))
					$this->set('rights_add', true);
				else
					$this->set('rights_add', false);
				if ($this->UserAuth->checkAcces($project_id, 'project_role_edit'))
					$this->set('rights_actions', true);
				else
					$this->set('rights_actions', false);
			}
		} else {
			if ($this->UserAuth->checkAcces($this->data['Role']['project_id'], 'project_role_add')) {
				if ($this->data['Role']['access'] == 1)
					$this->data['Role']['access'] = 'yes';
				else
					$this->data['Role']['access'] = 'no';
				$this->Project->Role->query("INSERT INTO `webx2`.`roles` (`user_id` ,`project_id` ,`status_id` ,`access`)
											VALUES ('".$this->data['Role']['user_id']."', '".$this->data['Role']['project_id']."', 
													'".$this->data['Role']['status_id']."', '".$this->data['Role']['access']."');");
				$this->Session->setFlash('Un intervenant a bien été ajouté.');
			} else {
				$this->Session->setFlash("You don't have the right to add this role");
			}
			$this->redirect('/' . $this->data['Role']['project_name'] . '/'. $this->data['Role']['project_id'] . '/users/lists');
		}
	}

	/**
	 * delrole deletes the stakeholder given in parameter
	 *
	 * @param integer $user_id id of stakeholder to del
	 * @return void
	 * @author Romain Venturi 
	 */
	public function delrole($user_id)
	{
		$project_id = $this->params['projectId'];
		$project_name = $this->params['projectName'];
		if (!$this->UserAuth->checkAcces($project_id, 'project_role_del')) {
			$this->Session->setFlash('Failure, you don\'t have the right to delete.');
		} else {
			$this->Project->Role->query("DELETE FROM roles WHERE project_id=$project_id AND user_id=$user_id");
			$this->Session->setFlash("A stockholder has been deleted");
		}
		$this->redirect('/' . $project_name . '/'. $project_id . '/users/lists');
	}
	
	/**
	 * viewrole displays details about the stakeholder given in parameter
	 *
	 * @param integer $user_id id of stakeholder to display
	 * @return void
	 * @author Romain Venturi 
	 */
	public function viewrole($user_id)
	{
		$project_id = $this->params['projectId'];
		$this->set('project_id', $project_id);
		$this->set('project_name', $this->params['projectName']);
		if ($project_id != null) {
			$this->UserAuth->checkPermission($project_id);
			$this->User->unbindModel(array('belongsTo' => array('Company'), 'hasMany' => array('Role')));
			$this->set('currentUser', $this->User->FindAllById($user_id));
			$this->set('statusList', $this->Status->findAll());
			$this->set('userRole', $this->Project->Role->findAllByUserId($user_id));
		}
		if (empty($this->data) == false) {
			if ($this->UserAuth->checkAcces($project_id, 'project_role_edit')) {
				$this->Project->Role->query("UPDATE `roles` SET `status_id` = '".$this->data['Role']['status_id']."',
`access` = '".$this->data['Role']['access']."' WHERE `roles`.`user_id` =".$user_id." AND `roles`.`project_id` =".$project_id." ;");
				$this->Session->setFlash('Role updated.');
			} else {
				$this->Session->setFlash("You don't have the right to modify this role");		
			}
			$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/users/lists');
		}
	}

	/**
	 * randomStr generates a random string as password
	 *
	 * @param integer $car number of caracters of the result string
	 * @return string
	 * @author Romain Venturi 
	 */
	public function randomStr($car)
	{ 
		$string = ""; 
		$chaine = "abcdefghijklmnpqrstuvwxy"; 
		srand((double)microtime()*1000000); 
		for($i=0; $i<$car; $i++) { 
			$string .= $chaine[rand()%strlen($chaine)]; 
		} 
		return $string; 
	}

	/**
	 * adduser adds a user.
	 *
	 * @return void
	 * @author Romain Venturi 
	 */
	public function adduser()
	{
		$project_id = $this->params['projectId'];
		$this->set('project_id', $project_id);
		$this->set('project_name', $this->params['projectName']);
		$this->set('clientList', $this->Company->findAll());		
		if ($project_id != null) {
			$this->UserAuth->checkPermission($project_id);
		}
		if (!empty($this->data)) {
			if ($this->UserAuth->checkAcces($project_id, 'project_user_add')) {
				if ($this->data['User']['pass'] == 'oui') {
					$gen_pass = randomStr(10);
					$this->data['User']['password'] = md5($gen_pass);
					if ($this->User->save($this->data['User'])) {
						
						$idUser = $this->User->getLastInsertId();
						if(is_uploaded_file($this->data['User']['file']['tmp_name'])) {
							$extensions = array('.png', '.gif', '.jpg', '.jpeg');
							$extension = strrchr($this->data['User']['file']['name'], '.');
							if (in_array($extension, $extensions))
							{
								$picture_temp = $this->data['User']['file']['tmp_name'];
								$picture = $this->data['User']['file']['name'];
								move_uploaded_file($picture_temp, WWW_ROOT.'/img/users/'.$idUser.$extension);
					  			$this->User->query("UPDATE users SET image = 'users/".$idUser.$extension."' WHERE id = '".$idUser."'");
							} else {
								$this->Session->setFlash('The image : '.$this->data['User']['file']['name'].' couldn\'t be loaded.');
							}
						}
						
						$headers ='From: <'.$this->data['User']['mail'].'>'."\n";
						$headers .='Content-Type: text/plain; charset="iso-8859-1"'."\n";
						$headers .='Content-Transfer-Encoding: 8bit';
						mail($this->data['User']['mail'], 'Inscription Web Exchange 2.0',
							'Bonjour, vous trouverez ci-joint vos informations de connexion.\n
								Login : '.$this->data['User']['login'].'\n
								Mot de passe : '.$gen_pass, $headers);
						
						$this->Session->setFlash('The user has been added.');
						$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/users/lists');
					} else {
						$this->data['User']['password'] = "";
						$this->data['User']['password(confirm)'] = "";
					}
				} else {
					$this->data['User']['password'] = md5($this->data['User']['password']);
					$this->data['User']['password(confirm)'] = md5($this->data['User']['password(confirm)']);
					if (($this->data['User']['password'] == $this->data['User']['password(confirm)']) && $this->User->save($this->data['User'])) {
						
						$idUser = $this->User->getLastInsertId();
						if(is_uploaded_file($this->data['User']['file']['tmp_name'])) {
							$extensions = array('.png', '.gif', '.jpg', '.jpeg');
							$extension = strrchr($this->data['User']['file']['name'], '.');
							if (in_array($extension, $extensions))
							{
								$picture_temp = $this->data['User']['file']['tmp_name'];
								$picture = $this->data['User']['file']['name'];
								move_uploaded_file($picture_temp, WWW_ROOT.'/img/users/'.$idUser.$extension);
					  			$this->User->query("UPDATE users SET image = 'users/".$idUser.$extension."' WHERE id = '".$idUser."'");
							} else {
								$this->Session->setFlash('The image : '.$this->data['User']['file']['name'].' couldn\'t be loaded.');
							}
						}
						
						$this->Session->setFlash('The user has been added.');
						$this->redirect('/' . $this->params['projectName'] . '/'. $this->params['projectId'] . '/users/lists');
					} else {
						$this->Session->setFlash('Bad confirm password.');
						$this->data['User']['password'] = "";
						$this->data['User']['password(confirm)'] = "";
					}
				}
			} else {
				$this->Session->setFlash("You don't have the right to add this user");
				$this->redirect('/' . $project_name . '/'. $project_id . '/users/lists');
			}
		}
	}
	
	/**
	 * del deletes the user given in parameter
	 *
	 * @param integer $user_id id of user to del
	 * @return void
	 * @author Romain Venturi 
	 */
	public function del($user_id)
	{
		$this->User->query("DELETE FROM users WHERE id=".$user_id);
		$this->Project->Role->query("DELETE FROM roles WHERE user_id=".$user_id);
		$this->Session->setFlash("A user has been deleted");
		$this->redirect('/users/liste');
	}
	
	/**
	 * add adds a user without having selected a project.
	 *
	 * @return void
	 * @author Romain Venturi 
	 */
	public function add()
	{
		$this->set('clientList', $this->Company->findAll());		
		if (!empty($this->data)) {
			if ($this->data['User']['pass'] == 'oui') {
				$gen_pass = randomStr(10);
				$this->data['User']['password'] = md5($gen_pass);
				if ($this->User->save($this->data['User'])) {
					
					$headers ='From: <'.$this->data['User']['mail'].'>'."\n";
					$headers .='Content-Type: text/plain; charset="iso-8859-1"'."\n";
					$headers .='Content-Transfer-Encoding: 8bit';
					mail($this->data['User']['mail'], 'Inscription Web Exchange 2.0',
						'Bonjour, vous trouverez ci-joint vos informations de connexion.\n
							Login : '.$this->data['User']['login'].'\n
							Mot de passe : '.$gen_pass, $headers);
					
					$this->Session->setFlash('The user has been added.');
					$this->redirect('/admin');
				} else {
					$this->data['User']['password'] = "";
					$this->data['User']['password(confirm)'] = "";
				}
			} else {
				$this->data['User']['password'] = md5($this->data['User']['password']);
				$this->data['User']['password(confirm)'] = md5($this->data['User']['password(confirm)']);
				if (($this->data['User']['password'] == $this->data['User']['password(confirm)']) && $this->User->save($this->data['User'])) {
					$this->Session->setFlash('The user has been added.');
					$this->redirect('/admin');
				} else {
					$this->Session->setFlash('Bad confirm password.');
					$this->data['User']['password'] = "";
					$this->data['User']['password(confirm)'] = "";
				}
			}
		}
	}

	/**
	 * view displays details about the user given in parameter
	 *
	 * @param integer $user_id id of stakeholder to display
	 * @return void
	 * @author Romain Venturi 
	 */
	public function view($user_id)
	{
		$project_id = $this->params['projectId'];
		$this->set('project_id', $project_id);
		$this->set('project_name', $this->params['projectName']);
		if ($project_id != null) {
			$this->UserAuth->checkPermission($project_id);
			$currentUser = $this->User->FindAllById($user_id);
			$this->set('currentUser', $currentUser);
			$this->set('company', $this->Company->findAllById($currentUser['0']['User']['company_id']));
			$this->Status->unbindmodel(array('hasMany' => array('Role')));
			$statusList = $this->Status->findAll();
			$this->set('statusList', $statusList);
		}
	}
	
	/**
	 * view displays details about the user given in parameter without having selected a project
	 *
	 * @param integer $user_id id of stakeholder to display
	 * @return void
	 * @author Romain Venturi 
	 */
	public function viewuser($user_id)
	{
		$currentUser = $this->User->FindAllById($user_id);
		$this->set('currentUser', $currentUser);
		$this->set('company', $this->Company->findAllById($currentUser['0']['User']['company_id']));
		$this->Status->unbindmodel(array('hasMany' => array('Role')));
		$statusList = $this->Status->findAll();
		$this->set('statusList', $statusList);
	}
	
	public function reconnect() {
		$cookie_user = $this->Cookie->read('User');
		if ($user = $this->User->validateCookie($cookie_user['login'], $cookie_user['password'])) {
			$url = $this->Session->read('url');
			$this->Session->write('User', $user);
			$this->Session->setFlash(__('flash_loggin_good', true));
			$this->redirect('/'.$url);			
		}
	}

	public function login()
	{
		if (empty($this->data) == false) {
			if (($user = $this->User->validateLogin($this->data['User'])) == true) {
				$url = $this->Session->read('url');
				$this->Session->write('User', $user);
				if ($this->data['User']['remember_me']) {
					$cookie = array();
                    $cookie['login'] = $this->data['User']['login'];
                    $cookie['password'] = md5($this->data['User']['password']);
                    $this->Cookie->write('User', $cookie, true, '+2 weeks');
				}
				$this->Session->setFlash(__('flash_loggin_good', true));
				$this->redirect('/'.$url);
			} else {
				$this->Session->setFlash(__('flash_loggin_error', true));
			}
		} else {
			$this->reconnect();
		}
	}
	
	public function logout()
	{
		$this->Session->destroy('User');
		$this->Session->destroy('url');
		$this->Session->setFlash(__('flash_loggin_logout', true));
		$this->Cookie->del('User');
		$this->redirect('login');
	}
	
	private function __validateLoginStatus()
	{
		if ($this->action != 'login' && $this->action != 'logout') {
			if ($this->Session->check('User') == false) {
				$this->log("Look like {$_SESSION['User']} just logged in.", LOG_DEBUG);
				$this->redirect('login');
				$this->Session->setFlash(__('flash_loggin_needed', true));
			}
		}
	}
	
	/**
	 * Edit information from a user
	 *
	 * @return void
	 * @author Rémi Peron
	 **/
	function edit()
	{
		$user = $this->Session->read('User');
		$this->set ('image', $user['User']['image']);
		if (empty($this->data)) {
			// pr ($this->Session->read('User'));
			$this->data['User'] = $user['User'];
			$this->data['User']['password'] = "";
		} else {
			$this->Session->setFlash(__('User info updated', true));
			$this->data['User']['login'] = $user['User']['login'];
			if ($this->data['User']['password'] == "" ||
				($this->data['User']['password'] != $this->data['User']['password_confirmation'])) {
					$this->data['User']['password'] = $user['User']['password'];
				}
			else {
				$this->data['User']['password'] = md5($this->data['User']['password']);
			}
			if ($this->User->save($this->data['User'])) {
				$this->User->id = $this->data['User']['id'];
				if(is_uploaded_file($this->data['User']['file']['tmp_name'])) {
					$extensions = array('.png', '.gif', '.jpg', '.jpeg');
					$extension = strrchr($this->data['User']['file']['name'], '.');
					if (in_array($extension, $extensions))
					{
						$picture_temp = $this->data['User']['file']['tmp_name'];
						$picture = $this->data['User']['file']['name'];
						move_uploaded_file($picture_temp, WWW_ROOT.'img/users/'.$this->data['User']['id'].$extension);
			  			$this->User->query("UPDATE users SET image = 'users/".$this->User->id .$extension."' WHERE id = '".$this->data['User']['id']."'");
					} else {
						$this->Session->setFlash('The image : '.$this->data['User']['file']['name'].' couldn\'t be loaded.');
					}
				}

				$user = $this->User->read();
				$this->Session->write('User', $user);
			}
		}
	}
	
}

?>